using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Wolfpack.Contrib.Checks.NuGet
{
    [DataContract]
    public class NuGetPackageInfos
    {
        [DataMember]
        public DateTime LastChecked { get; set; }

        [DataMember]
        private readonly Dictionary<string, NuGetPackageInfo> _packages;

        public NuGetPackageInfos()
        {
            _packages = new Dictionary<string, NuGetPackageInfo>();
        }

        public NuGetPackageInfos(IEnumerable<NuGetPackageInfo> packages)
        {
            packages.ToList().ForEach(Add);
        }

        public NuGetPackageInfo this[string name]
        {
            get { return _packages[NormaliseKey(name)]; }
        }

        public void Add(NuGetPackageInfo package)
        {
            _packages.Add(NormaliseKey(package.Name), package);
        }

        public bool ContainsKey(string key)
        {
            return _packages.ContainsKey(NormaliseKey(key));
        }

        public void Remove(string key)
        {
            _packages.Remove(NormaliseKey(key));
        }

        public List<KeyValuePair<string, NuGetPackageInfo>> ToList()
        {
            return _packages.ToList();
        }

        private static string NormaliseKey(string key)
        {
            return key.ToLowerInvariant();
        }
    }
}